package com.zijie.hosptal.aop;

import com.zijie.hosptal.mapper.LogMapper;
import com.zijie.hosptal.pojo.po.Log;
import com.zijie.hosptal.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class OperationLogAspect {

    @Autowired
    private LogMapper logMapper;

    @Around("@annotation(com.zijie.hosptal.aop.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取开始时间
        long startTime = System.currentTimeMillis();
        
        // 获取方法的类名和方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        // 获取操作人姓名，可以通过获取 SecurityContext 或者通过方法参数传递
        String userName = ThreadLocalUtil.get("name"); //
        
        // 执行目标方法
        Object result = joinPoint.proceed();
        
        // 获取方法执行的耗时
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        // 记录日志
        com.zijie.hosptal.pojo.po.Log logEntry = new Log();
        logEntry.setUserName(userName);
        logEntry.setAllName(className);
        logEntry.setName(methodName);
        logEntry.setOperationTime(LocalDateTime.now());
        logEntry.setLongTime(duration);

        // 保存到数据库
        logMapper.insert(logEntry);

        return result;
    }
}
